import Konva from "konva";
import { Draw } from "../Draw/Draw";
import { VoidFun } from "../Interface/Pptx";
import { ColorMatchType } from "../Interface/ColorMatch";

// eslint-ignore/no-unsafe-function-type
export async function nextTick(fn?: VoidFun) {
  const callback = window.requestIdleCallback || window.setTimeout;
  return Promise.resolve().then(() => callback(() => fn && fn()));
}

/** 获取唯一ID */
export function getUniqueId() {
  return Math.random().toString(36).substring(2);
}

/** 获取随机颜色 */
export function getRandomColor() {
  return "#" + Math.random().toString(16).slice(2, 8);
}

/** 判断当前是否处于预览状态 */
export function isPreview() {
  return Boolean(
    document.body.querySelector(".konva-root-preview") &&
      document.fullscreenElement
  );
}

// shortcut 快捷键工具函数
export const isApple =
  typeof navigator !== "undefined" && /Mac OS X/.test(navigator.userAgent);

export const isIOS =
  typeof navigator !== "undefined" && /iPad|iPhone/.test(navigator.userAgent);

export function isMod(evt: KeyboardEvent | MouseEvent) {
  return isApple ? evt.metaKey : evt.ctrlKey;
}

// 判断参数非空
// eslint-disable-next-line
export function isEmpty(value: any) {
  return value === null || value === undefined || value === "";
}

// 向剪切板写入内容
export function writeClipboard(text: string) {
  const textarea = document.createElement("textarea");
  document.body.appendChild(textarea);
  // 隐藏此输入框
  textarea.style.position = "fixed";
  textarea.style.clip = "rect(0 0 0 0)";
  textarea.style.top = "10px";
  // 赋值
  textarea.value = text;
  // 选中
  textarea.select();
  // 复制
  document.execCommand("copy", true);
  // 移除输入框
  document.body.removeChild(textarea);
}

// 读取剪切板内容
export function readClipboard() {
  return new Promise<string>((resolve) => {
    const el = document.createElement("textarea");
    document.body.appendChild(el);
    el.style.position = "fixed";
    el.style.clip = "rect(0 0 0 0)";
    el.style.top = "10px";
    el.select();
    document.execCommand("paste");
    nextTick(() => {
      const clipboardContent = el.value.trim();
      document.body.removeChild(el);
      resolve(clipboardContent);
    });
  });
}

/** 辅助函数 - 获取配色指定类型的值 */
export function getColorMatch(draw: Draw, type: ColorMatchType) {
  const colorScheme = draw.getColorScheme();
  const color = colorScheme.getColorMatch()[type];

  // 如果是 string 类型，则转成 hex
  if (typeof color === "string") {
    // 需要保留 透明
    if (color === "transparent") return "transparent";

    const { r = 0, g = 0, b = 0 } = Konva.Util.colorToRGBA(<string>color) || {};
    return "#" + Konva.Util._rgbToHex(r, g, b);
  }
  // string[] 数组
  else return color;
}

/**
 * 转换 pptxtojson content 文本字段为 konva text + 样式
 * @param text string
 * @example "<p style="text-align: center;"><span style="color: #FFFFFF;font-size: 18pt;font-family: Calibri;">测试</span><span style="color: #FFFFFF;font-size: 18pt;font-family: Calibri;">文本</span></p>"
 * @returns { text:string,textFill }
 */
export function parsePptxText(text: string) {
  // 获取文本内容
  const content = text.replace(/<\/?[^>]*>/g, "");

  // 解析样式
  const fontFamily = text?.match(/font-family: (.*?);/)?.[1];
  const fontSize = text?.match(/font-size: (.*?);/)?.[1]?.replace(/pt/g, "");
  const color = text?.match(/color: (.*?);/)?.[1];

  return {
    text: content === "&nbsp;" ? "" : content,
    fontFamily,
    fontSize: Number(fontSize),
    color,
  };
}

/**
 * 将一维数组转成二维数组
 *  用于 解析 Line Points 数据，并创建 锚点
 */
export function parseLinePoints(points: number[], num?: number) {
  const result: number[][] = [];
  const n = num || 2;
  for (let i = 0; i < points.length; i += n) {
    result.push([...points].slice(i, i + n));
  }
  return result;
}

/**
 * 传入两个点，求可围成的田型点坐标
 */
export function getPointsPosition(
  x1: number,
  y1: number,
  x2: number,
  y2: number
) {
  // 左上
  const leftTop = [Math.min(x1, x2), Math.min(y1, y2)];
  // 中上
  const centerTop = [
    Math.abs(x1 - x2) / 2 + Math.min(x1, x2),
    Math.min(y1, y2),
  ];
  // 右上
  const rightTop = [Math.max(x1, x2), Math.min(y1, y2)];

  // 左中
  const leftCenter = [
    Math.min(x1, x2),
    Math.abs(y1 - y2) / 2 + Math.min(y1, y2),
  ];
  // 中中
  const centerCenter = [
    Math.abs(x1 - x2) / 2 + Math.min(x1, x2),
    Math.abs(y1 - y2) / 2 + Math.min(y1, y2),
  ];
  // 右中
  const rightCenter = [
    Math.max(x1, x2),
    Math.abs(y1 - y2) / 2 + Math.min(y1, y2),
  ];

  // 左下
  const leftBottom = [Math.min(x1, x2), Math.max(y1, y2)];
  // 中下
  const centerBottom = [
    Math.abs(x1 - x2) / 2 + Math.min(x1, x2),
    Math.max(y1, y2),
  ];
  // 右下
  const rightBottom = [Math.max(x1, x2), Math.max(y1, y2)];

  return {
    leftTop,
    centerTop,
    rightTop,
    leftCenter,
    centerCenter,
    rightCenter,
    leftBottom,
    centerBottom,
    rightBottom,
  };
}
